package cn.flant.io.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class BytesMessageHandler extends MessageHandler {
	private byte[] byteBuffer = null;
	private InputStream input;
	private OutputStream output;

	public BytesMessageHandler() {
		this(5120);
	}

	public BytesMessageHandler(int size) {
		byteBuffer = new byte[size];
	}

	public int getBufferSize() {
		return byteBuffer.length;
	}

	public void setBufferSize(int size) {
		byteBuffer = new byte[size];
	}

	@Override
	public void onConnected(Socket socket) throws IOException {
		input = socket.getInputStream();
		output = socket.getOutputStream();
	}

	@Override
	public Object readMessage() throws IOException {
		int length = input.read(byteBuffer);
		if (length < 0) {
			return null;
		}
		byte[] data = new byte[length];
		System.arraycopy(byteBuffer, 0, data, 0, length);
		return data;
	}

	@Override
	public void sendMessage(Object message) throws IOException {
		byte[] datas = (byte[]) message;
		output.write(datas);
		output.flush();
	}

	@Override
	public void onClosed() {
		if (input != null) {
			try {
				input.close();
			} catch (IOException e) {
			}
			input = null;
		}
		if (output != null) {
			try {
				output.close();
			} catch (IOException e) {
			}
			output = null;
		}
	}
}
